//
//  PublicUtil.m
//  BaseProject
//
//  Created by LiuLei on 16/5/17.
//  Copyright © 2016年 LiuLei. All rights reserved.
//

#import "PublicUtil.h"
#import <ifaddrs.h>
#import <arpa/inet.h>

@implementation PublicUtil

+ (NSString *)formatFloatNum:(double)num{
    
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@"###,##0.00;"];
    NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:num]];
    
    return formattedNumberString;
}


// Get IP Address
+ (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}


#pragma mark -- 字典转JSON
//NSJSONWritingPrettyPrinted  是有换位符的。
//如果NSJSONWritingPrettyPrinted 是nil 的话 返回的数据是没有换位符的
+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

#pragma mark -- 字符串尺寸
+ (CGSize)SizeForString:(NSString *)str WithFont:(UIFont *)font AndWidth:(NSInteger)width
{
    if (!str)
    {
        return CGSizeZero;
    }

    NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:str attributes:attrsDictionary];
    
    CGRect paragraphRect =
    [attributedText boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                 options:(NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                 context:nil];
    CGSize returnSize = CGSizeMake(ceilf(paragraphRect.size.width), ceilf(paragraphRect.size.height));
    
    return returnSize;
}


//  NSAttributedString 专用
+ (CGFloat)heightForLabelWithNSAttributedString:(NSAttributedString *)attrStr labelWidth:(CGFloat)labelWidth
{
    CGFloat titleHeight;
    
    NSStringDrawingOptions options =  NSStringDrawingUsesLineFragmentOrigin;
    CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(labelWidth, CGFLOAT_MAX)
                                        options:options
                                        context:nil];
    titleHeight = ceilf(rect.size.height);
    
    return titleHeight+2;  // 加两个像素,防止emoji被切掉.
}

// 计算 普通text 对应的高度
+ (CGFloat)heightForCellWithText:(NSString *)contentText fontSize:(UIFont *)labelFont labelWidth:(CGFloat)labelWidth
{
    CGFloat titleHeight = 0;
    if ([contentText length])
    {
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:contentText
                                                                             attributes:@{ NSFontAttributeName:labelFont}];
        titleHeight = [self heightForLabelWithNSAttributedString:attributedText labelWidth:labelWidth];
    }
    
    return titleHeight;
}


+ (NSAttributedString *)getMutableStringWithStr:(NSString *)str withLineSpace:(NSInteger )space{
    /**调整label的行间距*/
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:space];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
    
    //    lb_content.attributedText = [self getMutableStringWithStr:spec.content withLineSpace:4];
    //    [lb_content sizeToFit];
    
    return attributedString;
}

+ (NSAttributedString *)GetMutableStringWithStr:(NSMutableAttributedString *)str withLineSpace:(NSInteger )space{

    /**调整label的行间距*/
//    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:space];
    [str addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
    
    //    lb_content.attributedText = [self getMutableStringWithStr:spec.content withLineSpace:4];
    //    [lb_content sizeToFit];
    
    return str;
    
}
#pragma mark 颜色转换为图片

+(UIImage*) createImageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
#pragma mark - Date 相关

+ (NSDate *)getNSDateFromString:(NSString *)dateStr
{
    //
    //    CST -06:00 美国中部标准时间
    //    CCT +08:00 中国标准时间
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];   //实例化一个NSDateFormatter对象
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CCT"]];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];  //设定时间格式,这里可以设置成自己需要的格式
    //    NSDate *date =[dateFormat dateFromString:@"1980-01-01 00:00:01"];
    
    NSDate *destDate =[dateFormat dateFromString:dateStr];
    
    return destDate;
}

// 根据日期返回NSDate对象(日期格式: 2014-01-02)
+ (NSDate *)getNSDateFromSimpleDateString:(NSString *)dateStr
{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];   //实例化一个NSDateFormatter对象
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CCT"]];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];  //设定时间格式,这里可以设置成自己需要的格式
    NSDate *destDate =[dateFormat dateFromString:dateStr];
    
    return destDate;
}

// 根据NSDate返回String对象(格式: 2014/01/02)
+ (NSString *)getStringFromNSDate:(NSDate *)destDate
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    
    return [dateFormatter stringFromDate:destDate];
}


+ (NSString *)getChineseWeekdayWithDateString:(NSString *)dateStr
{
    NSString *weekStr=nil;
    NSDate *destDate = [self getNSDateFromString:dateStr];
    
    if (!destDate)
    {
        NSLog(@"NIL ERROR!");
    }
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSInteger unitFlags = NSCalendarUnitWeekday | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:destDate];
    
    NSInteger week = [comps weekday];
    NSInteger month = [comps month];
    NSInteger day = [comps day];
    
    if(week==1)
    {
        weekStr=@"周日";
    }else if(week==2){
        weekStr=@"周一";
        
    }else if(week==3){
        weekStr=@"周二";
        
    }else if(week==4){
        weekStr=@"周三";
        
    }else if(week==5){
        weekStr=@"周四";
        
    }else if(week==6){
        weekStr=@"周五";
        
    }else if(week==7){
        weekStr=@"周六";
    }
    else {
        NSLog(@"error!");
    }
    
    NSString *destStr = [NSString stringWithFormat:@"%@  %ld月%ld日", weekStr, (long)month, (long)day];
    
    return destStr;
}

+ (NSString *)getTimeStrWithString:(NSString *)dateStr
{
    NSDate *destDate = [self getNSDateFromString:dateStr];
    if (!destDate)
    {
        NSLog(@"NIL ERROR!");
    }
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSInteger unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:destDate];
    
    NSInteger hour = [comps hour];
    NSInteger minute = [comps minute];
    
    NSString *destStr = [NSString stringWithFormat:@"%02ld:%02ld", (long)hour, (long)minute];
    
    return destStr;
}

+ (NSString *)getTimeStrWithString:(NSString *)dateStr FormatterStr:(NSString *)fStr
{
    NSDate *destDate = [self getNSDateFromString:dateStr];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    if (fStr)
    {
        [dateFormatter setDateFormat:fStr];
    }
    else
    {
        [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    }
    
    return [dateFormatter stringFromDate:destDate];
}

#pragma mark - 富文本部分字体飘灰 text:源   highlightText:高亮部分  stringColor:不高亮时候显示的颜色   highlightColor:高亮字体的颜色  value:高亮字体大小
+ (NSMutableAttributedString *)setupAttributeString:(NSString *)text highlightText:(NSString *)highlightText  stringColor:(UIColor *)stringColor  highlightColor:(UIColor *)highlightColor  highlightValue:(id)value {
    NSRange hightlightTextRange = [text rangeOfString:highlightText options:NSCaseInsensitiveSearch];
    //    NSArray * textArr = [text componentsSeparatedByString:@"("];
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:text];
    NSRange textRange = [text rangeOfString:text];
    
    [attributeStr addAttribute:NSForegroundColorAttributeName
                         value:stringColor
                         range:textRange];
    [attributeStr addAttribute:NSFontAttributeName value:value range:textRange];
    if (hightlightTextRange.length > 0) {
        [attributeStr addAttribute:NSForegroundColorAttributeName
                             value:highlightColor
                             range:hightlightTextRange];
        return attributeStr;
    }
    return attributeStr;
}
#pragma mark -  延时执行

+ (void)doSomething:(void (^)(void))functions
     afterDelayTime:(double)delayInSeconds
{
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void)
                   {
                       functions();
                   });
}

+ (void)doSomethingLater:(void (^)(void))functions
{
    [self doSomething:functions
               afterDelayTime:0.8];
}

#pragma mark - 主线程执行

+ (void)doSomethingOnMainThread:(void (^)(void))functions
{
    dispatch_async(dispatch_get_main_queue(), ^{
        functions();
    });
}

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0,0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context =UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *img =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}


@end
